# coding=utf-8

"""httplib的一层封装，更易于使用

.. doctest:: 

    >>> http_obj = cofHttp.Http(url, 80)
    >>> http_obj.set_header(header)
    >>> http_obj.post("/syslog", self.data)
"""

__author__ = 'Administrator'

import urllib2
import cookielib

import lib.log as LLog

logger = LLog.Logger()


class Http(object):
    """对GET/POST进行了封装，让代码更简短易读
    :class:`cof.http.Http` 先初始化

    * `METHOD`: 默认请求方法
    """

    METHOD = "GET"

    def __init__(self, host, port=80, url='', ssl=False):
        """
        使用httplib库进行操作
        """
        import httplib
        self.host = host
        self.port = str(port)
        if self.port == "":
            self.port = None
        self.url = url
        self.header = dict()
        # 请求body
        self.params = None
        if ssl:
            self.conn = httplib.HTTPSConnection(self.host, self.port)
        else:
            # self.conn = httplib.HTTPConnection("127.0.0.1", 8888)
            self.conn = httplib.HTTPConnection(self.host, self.port)

        # self.conn.set_tunnel(self.host, int(self.port))

    def parse_url(self):
        pass

    def set_header(self, header):
        """
        设置http请求头，可以设置AccessToken
        """
        self.header = header

    def get(self, url):
        conn = self.conn
        conn.request(method="GET", url=url, headers=self.header)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "GET " + self.host + url
        else:
            res["request"] = "GET " + self.host + ":" + self.port + url
        res["code"] = response.status
        res["data"] = response.read()
        logger.info(url)
        logger.info("===============================")
        logger.info(res["data"])
        conn.close()
        return res

    def post(self, url, params):
        conn = self.conn
        conn.request(method="POST", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        # print params
        res = dict()
        if self.port == None:
            res["request"] = "POST " + self.host + url + ",body=" + params
        else:
            res["request"] = "POST " + self.host + ":" + self.port + url + ",body=" + params
        res["code"] = response.status
        res["data"] = response.read()
        logger.info(url)
        logger.info(params)
        logger.info("===============================")
        logger.info(res["data"])
        conn.close()
        return res

    def delete(self, url, params=None):
        conn = self.conn
        conn.request(method="DELETE", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "DELETE " + self.host + url
        else:
            res["request"] = "DELETE " + self.host + ":" + self.port + url
        res["code"] = response.status
        res["data"] = response.read()
        conn.close()
        return res

    def patch(self, url, params):
        conn = self.conn
        conn.request(method="PATCH", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "PATCH " + self.host + url + ",body=" + params
        else:
            res["request"] = "PATCH " + self.host + ":" + self.port + url + ",body=" + params
        res["code"] = response.status
        res["data"] = response.read()
        conn.close()
        return res

    def put(self, url, params):
        conn = self.conn
        conn.request(method="PUT", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "PUT " + self.host + url + ",body=" + params
        else:
            res["request"] = "PUT " + self.host + ":" + self.port + url + ",body=" + params
        res["code"] = response.status
        res["data"] = response.read()
        conn.close()
        return res


class Http2(object):
    """
    使用urllib2 http库进行调用
    """
    def __init__(self, host, port, url):
        self.host = host
        self.port = port
        self.header = dict()
        # 请求body
        self.params = None

        self.req_url = 'http://' + host + ':' + port + url
        self.conn = urllib2.Request(self.req_url)

    def set_header(self, header):
        # print header
        for k in header:
            v = header[k]
            self.conn.add_header(k, v)

    def post(self, url, params):
        response = urllib2.urlopen(self.conn, params)
        res = response.read()
        return res


class Http3(object):
    def __init__(self, host, port, url=''):
        cookies = cookielib.LWPCookieJar()

        handlers = [
            urllib2.HTTPHandler(),
            urllib2.HTTPSHandler(),
            urllib2.HTTPCookieProcessor(cookies)
        ]

        self.opener = urllib2.build_opener(*handlers)
        self.req_url = 'http://' + host + ':' + str(port)

    def set_header(self, header):
        # print header
        for k in header:
            v = header[k]
            self.opener.addheaders.append((k, v))

    def post(self, url, params):
        url = self.req_url + url
        req = urllib2.Request(url)
        return self.opener.open(req, params).read()

    def get(self, url):
        url = self.req_url + url
        req = urllib2.Request(url)
        return self.opener.open(req).read()

class Http4(object):
    """对GET/POST进行了封装，让代码更简短易读 添加了获取jsession
    :class:`cof.http.Http` 先初始化

    * `METHOD`: 默认请求方法
    """

    METHOD = "GET"

    def __init__(self, host, port=80, url='', ssl=False):
        """
        使用httplib库进行操作
        """
        import httplib
        self.host = host
        self.port = str(port)
        if self.port == "":
            self.port = None
        self.url = url
        self.header = dict()
        # 请求body
        self.params = None
        if ssl:
            self.conn = httplib.HTTPSConnection(self.host, self.port)
        else:
            self.conn = httplib.HTTPConnection(self.host, self.port)

    def parse_url(self):
        pass

    def set_header(self, header):
        """
        设置http请求头，可以设置AccessToken
        """
        self.header = header

    def get(self, url):
        conn = self.conn
        conn.request(method="GET", url=url, headers=self.header)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "GET " + self.host + url
        else:
            res["request"] = "GET " + self.host + ":" + self.port + url
        res["code"] = response.status
        res["data"] = response.read()
        logger.info(url)
        logger.info("===============================")
        logger.info(res["data"])
        return res

    def post(self, url, params):
        conn = self.conn
        conn.request(method="POST", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        jsession = ""
        cookie = response.getheader("set-cookie")
        if cookie != None:
            start = cookie.find("JSESSIONID=")
            end = cookie.find(";", start+11)
            jsession = str(cookie[start+11:end])

        # print params
        res = dict()
        if self.port == None:
            res["request"] = "POST " + self.host + url + ",body=" + params
        else:
            res["request"] = "POST " + self.host + ":" + self.port + url + ",body=" + params
        res["code"] = response.status
        res["data"] = response.read()
        res["jsession"] = jsession
        logger.info(url)
        logger.info(params)
        logger.info("===============================")
        logger.info(res["data"])
        return res

    def delete(self, url, params=None):
        conn = self.conn
        conn.request(method="DELETE", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "DELETE " + self.host + url
        else:
            res["request"] = "DELETE " + self.host + ":" + self.port + url
        res["code"] = response.status
        res["data"] = response.read()
        return res

    def patch(self, url, params):
        conn = self.conn
        conn.request(method="PATCH", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "PATCH " + self.host + url + ",body=" + params
        else:
            res["request"] = "PATCH " + self.host + ":" + self.port + url + ",body=" + params
        res["code"] = response.status
        res["data"] = response.read()
        return res

    def put(self, url, params):
        conn = self.conn
        conn.request(method="PUT", url=url, headers=self.header, body=params)
        response = conn.getresponse()
        res = dict()
        if self.port == None:
            res["request"] = "PUT " + self.host + url + ",body=" + params
        else:
            res["request"] = "PUT " + self.host + ":" + self.port + url + ",body=" + params
        res["code"] = response.status
        res["data"] = response.read()
        return res


class HttpCurl(object):
    """
    使用
    """
    def get(self):
        pass


class HttpTornado(object):
    def __init__(self):
        from tornado.httpclient import HTTPClient
        self.conn = HTTPClient()

    """
    使用tornado库
    """
    def get(self, url):
        return self.conn.fetch(url)
        pass

    def put(self, url):
        from tornado.httpclient import HTTPRequest
        req = HTTPRequest(url, "PUT")
        self.conn.fetch(req)


class HttpInfo(object):
    def __init__(self):
        self.host = ""

    def get_host(self):
        return self.host
